'''
Created on 2013-5-7

@author: CL.Lam
'''
import os
from datetime import datetime as dt
from flask import session
from sqlalchemy.sql.expression import and_

from sys2do.util.common import _g
from sys2do.model import DBSession as db, qry, City, Province
from sys2do.util.logic_helper import getCurrentShopID, getAllPermission, \
    getAnyPermission, inAllGroup, inAnyGroup, getCurrentShopProfile, guessNo
from sys2do.constant import TAB_FLAG
from sys2do.util.decorator import trycatch


__all__ = ['getMaster', 'getActiveTab', 'getShopID', 'getShopPro',
           'getAllPermission', 'getAnyPermission',
           'inAllGroup', 'inAnyGroup', 'now', 'getCity', 'isImage', 'guessNotp',
           ]

def getMaster( name, order_by_col = None ):
    import sys2do.model as m
    clz = getattr( m, name )

    if not order_by_col: order_by = clz.sysCreateTime
    else: order_by = getattr( clz, order_by_col )

    if getattr( clz, 'iall' ) : return clz.iall( order_by = order_by )

    return db.query( clz ).filter( and_( clz.active == 0, ) ).order_by( order_by )



def getActiveTab():
    return session.get( TAB_FLAG, None )



def getShopID():
    return getCurrentShopID()


def getShopPro():
    return getCurrentShopProfile()

now = dt.now


def getCity( pid ):
    cs = qry( City ).filter( and_( City.active == 0, City.parent_code == Province.code, Province.id == pid ) ).order_by( City.name )
    return cs


@trycatch( False )
def isImage( n ):
    print n
    ext = os.path.splitext( n )[1][1:].lower()
    return ext in ['jpg', 'gif', 'png', 'bmp', 'jpeg']



guessNotp = guessNo
